require 'digest/sha2'

class User < ActiveRecord::Base
	
	has_and_belongs_to_many :roles

	validates_presence_of :username, :password
	
	validates_length_of		:password, :minimum => 5
	
	validates_uniqueness_of :username
	
	def password
		@password
	end

	def password=(clear_text_password)
		@password = clear_text_password
		self.password_salt = calculate_salt(rand)
		self.password_hash = User.calculate_password_hash(clear_text_password, password_salt)
	end

	def calculate_salt(number)
			raw_salt = self.object_id.to_s + number.to_s
			Digest::SHA256.hexdigest(raw_salt)[0..39]
	end
	
	def self.calculate_password_hash(clear_text_password, salt)
		Digest::SHA256.hexdigest(clear_text_password + salt)
	end
	
	def self.authenticate(username, password)
		user = User.find_by_username(username)
		if (user)
			if (user.password_hash != User.calculate_password_hash(password, user.password_salt))
				user = nil
			end
		end
		user	
	end
		
	def authorized?(object_name, operation_name)
		roles.detect do |role|
				role.permitted? object_name, operation_name
		end != nil
	end
	
end
